package com.h2cloud.JUCTest.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

import static com.h2cloud.JUCTest.TimeUtil.Sleeper.sleep;


@Slf4j(topic = "c.TestInterrupt")
public class TestInterrupt {
	public static void main(String[] args) {
		 test2();
//		test1();
	}

	private static void test2() {
		ReentrantLock lock = new ReentrantLock();

		Thread t1 = new Thread(() -> {
			log.debug("启动...");
			lock.lock();
			try {
				while (!Thread.currentThread().isInterrupted()) {
					log.debug("获得了锁");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				// 不响应中断的 lock，只设置打断标识，代码中自己去判断
				System.out.println("Thread.currentThread().isInterrupted() = " + Thread.currentThread().isInterrupted());
			} finally {
				lock.unlock();
				log.debug("释放了锁");
			}
		}, "t1");


		lock.lock();
		log.debug("获得了锁");
		t1.start();
		try {
			sleep(1);
			t1.interrupt(); // t1使用 lock()方法加锁，这里打断了也没用
			log.debug("执行打断");
			sleep(1);
		} finally {
			log.debug("释放了锁");
			lock.unlock();
		}
	}

	private static void test1() {
		ReentrantLock lock = new ReentrantLock();

		Thread t1 = new Thread(() -> {
			log.debug("启动...");
			try {
				lock.lockInterruptibly(); // 加锁（可打断的锁）
				log.debug("获得了锁");
			} catch (InterruptedException e) {
				e.printStackTrace();
				log.debug("等锁的过程中被打断");
			} finally {
				lock.unlock();
			}
		}, "t1");


		lock.lock();
		log.debug("获得了锁");
		t1.start();
		try {
			sleep(1);
			t1.interrupt();
			log.debug("执行打断");
		} finally {
			lock.unlock();
		}
	}
}
